import IMEventHandler from "@/utils/im";
import { bindPhone, wxLogin, bindPerson, clickShareLink } from "@/api/index";
import { autoGenerateName, reportRegisterLog } from "@/api/modules/career.js";

export default {
  data() {
    return {
      isAuthSetting: false,
      getUserInfoLoading: false,
      isNewUser: false,
      currentItem: {},
      currentIndex: 0,
    };
  },
  methods: {
    // 检测用户是否授权
    checkAuthSetting() {
      uni.getSetting({
        success: (res) => {
          if (res && res.authSetting && res.authSetting["scope.userInfo"])
            this.isAuthSetting = true;
        },
      });
    },
    getUserInfo(e) {
      if (e.detail.encryptedData) {
        this.login(true);
      }
    },
    login(needRelogin) {
      const that = this;
      this.getUserInfoLoading = true;
      uni.login({
        success: function (loginRes) {
          if (loginRes.code) {
            uni.setStorageSync("wx-code", loginRes.code);
            let param = {
              code: loginRes.code,
              rawData: "",
              signature: "",
              encryptedData: "",
              iv: "",
            };
            wxLogin(param).then((wxLoginRes) => {
              if (!wxLoginRes) return;
              let data = wxLoginRes.data || wxLoginRes;
              uni.setStorageSync("wx-session3rd", data.session3rd);
              uni.setStorageSync("openid", data.openid);
              //是否获得用户权限
              uni.getSetting({
                success(settingRes) {
                  if (settingRes.authSetting["scope.userInfo"]) {
                    uni.getUserInfo({
                      success(res) {
                        uni.setStorageSync("encryptedData", res.encryptedData);
                        uni.setStorageSync("iv", res.iv);
                        uni.setStorageSync("signature", res.signature);
                        that.isAuthSetting = true;
                        that.getUserInfoLoading = false;
                        if (needRelogin) {
                          uni.showToast({
                            title: "授权完成，请重新登录",
                            icon: "none",
                            duration: 2000,
                          });
                        }
                      },
                    });
                  }
                },
              });
            });
          }
        },
      });
    },
    handleInfo(item, index) {
      if (item) {
        this.currentItem = item;
        this.currentIndex = index;
      }
      uni.getUserInfo({
        success(res) {
          uni.setStorageSync("encryptedData", res.encryptedData);
          uni.setStorageSync("iv", res.iv);
          uni.setStorageSync("signature", res.signature);
        },
        fail(err) {
          uni.showToast({ icon: "none", title: "取消登录", duration: 2000 });
          // uni.reLaunch({ url: "/pages/index/index" });
        },
      });
    },
    //loginDialog手机号一键登录真正调用的方法，encryptedData会在app.vue里的login方法中获取到并存起来
    getPhoneNumber(e) {
      if (!e.detail.encryptedData) {
        uni.showToast({ icon: "none", title: "取消登录", duration: 2000 });
        // uni.reLaunch({ url: "/pages/index/index" });
      } else {
        uni.getSetting({
          success: (res) => {
            if (res && res.authSetting && res.authSetting["scope.userInfo"])
              this.isAuthSetting = true;
            this.handleBindPhone(e.detail);
          },
        });
      }
    },
    handleBindPhone(data) {
      let param = {
        mobileEncrypted: data.encryptedData,
        mobileIv: data.iv,
        spEncrypted: uni.getStorageSync("encryptedData"),
        spIv: uni.getStorageSync("iv"),
        session3rd: uni.getStorageSync("wx-session3rd"),
      };
      const isZhituUser = uni.getStorageSync("isZhituUser");
      if (isZhituUser) {
        param.regSource = "miniProgramZhitu"; //如果是职途相关页面登录要传注册来源
        uni.removeStorageSync("isZhituUser");
      }

      uni.showLoading({
        title: "正在登录",
        mask: true,
      });
      console.log("param", param);

      // return;
      bindPhone(param)
        .then((res) => {
          if (res.data && res.data.info && res.data.info.newRegister) {
            this.handleNewUser && this.handleNewUser();
            this.isNewUser = true;
          }
          if (res.status === "OK") {
            this.handleLogin(res.data.info.personId);

            if (this.isNewUser) {
              this.reportShareData(res.data.info.personId, "reg");
            } else {
              this.reportShareData(res.data.info.personId, "login");
            }
            //2025年5月14日注册成功后如果有sellerId，请求埋点接口
            
            const sellerId = uni.getStorageSync("sellerId");
            console.log('wxlogin sellerId',sellerId);
            if (sellerId) {
              this.reqReportRegisterLog(res.data.info.personId);
            }
            //新用户而且是职途用户就请求接口改一个特殊的名字
            if (isZhituUser && this.handleNewUser) {
              this.reqAutoGenerateName(res.data.info.personId);
            }
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: res.status_desc || "手机绑定异常",
            });
            if (this.setVisibility) {
              this.setVisibility(true);
            }
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            icon: "none",
            title: "手机绑定异常",
            duration: 2000,
          });
        });
    },
    reqReportRegisterLog(personId) {
      const params = {
        personId, //新用户的personId
        sellerId: uni.getStorageSync("sellerId"),
        project: "10", //10高考选科 20职业大全 30高考报志愿 40职途机
      };
      reportRegisterLog()
        .then((res) => {})
        .catch(() => {});
    },
    reqAutoGenerateName(personId) {
      const params = {
        personId,
      };
      autoGenerateName(params)
        .then((res) => {
          if (res.code == 200) {
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    handleLogin(personId) {
      uni.setStorageSync("person-id", "id" + personId);
      this.bindOpenId(personId);
      let isImLogin =
        getApp().globalData.tim && getApp().globalData.tim.getLoginUser();
      let isLogin = false;
      if (!isImLogin) {
        new IMEventHandler(() => {
          let currentPage = getCurrentPages()[0].route;
          if (currentPage.indexOf("loginMode") >= 0) {
            isLogin = true;
            uni.hideLoading();
            uni.showToast({ icon: "none", title: "登录成功" });
            this.handleJump(personId);
          }
        });
        setTimeout(() => {
          if (!isLogin) {
            getApp().globalData.tim && getApp().globalData.tim.logout();
            getApp().globalData.tim = null;
            uni.hideLoading();
            uni.showToast({ icon: "none", title: "登录成功" });
            this.handleJump(personId);
          }
        }, 5000);
      } else {
        uni.hideLoading();
        uni.showToast({ icon: "none", title: "登录成功" });
        this.handleJump(personId);
      }
    },
    // 绑定openid
    bindOpenId(personId) {
      const openId = uni.getStorageSync("openid");
      const params = {
        personId: personId,
        openId: openId,
      };
      bindPerson(params);
    },
    handleJump(personId) {
      // 各自处理
    },
    reportShareData(personId, type) {
      let shareCode = getApp().globalData.shareCode;
      if (!shareCode) return;
      clickShareLink({
        personId,
        uniqueCode: shareCode,
        type,
      });
    },
    // 前往登录页
    handleLoginPage() {
      let fullPath =
        getCurrentPages()[getCurrentPages().length - 1].$page.fullPath;
      let returnUrl = encodeURIComponent(fullPath);
      uni.navigateTo({
        url: "/pagesSub/public/loginMode/index?returnUrl=" + returnUrl,
      });
    },
  },
};
